package cn.wgx.commons.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * 二维码工具类
 */
//@Component
public class QRCode {

    private  int WIDTH = 300;

    private  int HIGHT = 300;

    private  String CHARSET = "utf-8";

    @Value("${qrcode.domain}")
    private  String domain = "file.sxycy.cn";

    @Value("${qrcode.port}")
    private  String port = "80";

    @Value("${qrcode.subffix}")
    private  String SUBFFIX = "png";

    @Value("${qrcode.path}")
    private  String FILE_PATH = "/upload/qrcode/";

    private  String PATH_PREFIX;

    private  String FULL_PATH ;

    @PostConstruct
    private void init(){
        PATH_PREFIX = this.getClass().getClassLoader().getResource("").getPath()+"../";
        FULL_PATH = PATH_PREFIX + FILE_PATH;
        File f = new File(FULL_PATH);
        if(!f.exists()){
            f.mkdirs();
        }
        System.out.println(FULL_PATH);
    }

    public static void main(String a[]){
        System.out.println(new QRCode().createQCode("www.baidu.com"));
    }

    public  String createQCode(String content) {
        if(FULL_PATH == null){
            init();
        }
        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//纠错等级L,M,Q,H
        hints.put(EncodeHintType.MARGIN, 2); //边距
        BitMatrix bitMatrix = null;
        String fileName = UUID.randomUUID() + ".png";
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HIGHT, hints);
            File f = new File(FULL_PATH + fileName);
            System.out.println(FULL_PATH + fileName);
            MatrixToImageWriter.writeToPath(bitMatrix, SUBFFIX, f.toPath());
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return FILE_PATH + fileName;
    }

}
